package top.vains.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import top.vains.dto.UserRoleDto;
import top.vains.entity.UserRole;
import top.vains.exception.CustomerException;
import top.vains.mapper.UserRoleMapper;
import top.vains.service.IUserRoleService;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author vains
 * @since 2020-02-17
 */
@Slf4j
@Service
public class UserRoleServiceImpl extends ServiceImpl<UserRoleMapper, UserRole> implements IUserRoleService {

    @Override
    public List<String> selectRoleDetails(Integer userId) {
        return baseMapper.selectRoleDetails(userId);
    }

    @Override
    public void updateUserRole(UserRoleDto userRoleDto) {
        if (userRoleDto == null) {
            throw new CustomerException("用户和角色的信息不能为空");
        }
        List<Integer> roleId = userRoleDto.getRoleId();
        log.info("先删除用户所有的角色，用户ID：", userRoleDto.getUserId());
        UpdateWrapper<UserRole> wrapper = new UpdateWrapper<>();
        wrapper.eq("user_id", userRoleDto.getUserId());
        baseMapper.delete(wrapper);
        if (CollectionUtils.isEmpty(roleId)) {
            log.info("如果角色信心是空的，则不添加新的角色信息");
            return;
        }
        log.info("将新的角色信息添加进去");
        roleId.forEach(e -> {
            UserRole userRole = new UserRole(null, userRoleDto.getUserId(), e);
            baseMapper.insert(userRole);
        });
    }
}
